#include "Flash.h"
#include "driver_flash.h"
#include "stdbool.h"
#include "stdlib.h"


bool IsAddressValid(uint32_t nAddr)
{
    if ((nAddr >= FLASH_START_ADDR) && (nAddr <= FLASH_END_ADDR))
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool Flash_Read(uint32_t nAddr, uint8_t *pData, uint16_t nLength)
{
    if (!IsAddressValid(nAddr) || (NULL == pData) || (nLength <= 0))
    {
        return false;
    }
    
    for (int i = 0; i < nLength; i++)
    {
        pData[i] = ReadByte(nAddr + i);
    }
	return true;
}


//bool Flash_Read_Page(uint32_t nAddr, uint8_t* readBuff, uint16_t nReadLength)
//{
//	bool bSuccess = true;
//	if((nAddr % FLASH_PAGE_SIZE != 0) || (NULL == readBuff) || (FLASH_PAGE_SIZE != nReadLength))
//	{
//		return false;
//	}
//	//逐字节读取数据
//	for(int i = 0; i < nReadLength; i++)
//	{
//		readBuff[i] = ReadByte(nAddr+i);
//	}
//	
//	return bSuccess;
//}

bool Flash_Erase_Page(uint32_t nAddr)
{
	bool bSuccess = true;
	if ((nAddr % FLASH_PAGE_SIZE != 0))//待擦除地址非页首地址
	{
		bSuccess = false;
	}
	else	//待擦除地址为页首地址
	{
		if (4 != ErasePage(nAddr))	//Flash操作成功的FLASH_COMPLETE对应枚举值为4
		{
			bSuccess = false;
		}
	}
	
	return bSuccess;
}

bool Flash_Write_Page(uint32_t nAddr, const uint8_t *pWriteBuff)
{
	if (NULL == pWriteBuff)
	{
		return false;
	}
	uint32_t *pTemp = (uint32_t*)pWriteBuff;
	for(int i = 0; i < FLASH_PAGE_SIZE;)
	{
		int16_t status = ProgramWord(nAddr, pTemp[i]);
		if (4 == status)
		{
			i += 4;
		}
		else
		{
			return false;
		}
	}
	
	return true;
}


bool Flash_Write(uint32_t nAddr, const uint8_t *pData, uint16_t nLength)
{
    if (!IsAddressValid(nAddr) || (NULL == pData) || (nLength <= 0))
    {
        return false;
    }
	bool bSuccess = true;
	uint32_t nPage = (nAddr - FLASH_START_ADDR) / FLASH_PAGE_SIZE;				//页地址
	uint32_t nOffset = (nAddr - FLASH_START_ADDR) % FLASH_PAGE_SIZE;				//页内偏移地址
	uint32_t nRemain = FLASH_PAGE_SIZE - nOffset;			//剩余空间大小
	
	if (nLength <= nRemain)			//当前页剩余空间可以容纳待写数据
	{
		uint8_t buff[FLASH_PAGE_SIZE] = {0};
		//读取当前页的数据
		bSuccess = Flash_Read(FLASH_START_ADDR + nPage * FLASH_PAGE_SIZE, buff, FLASH_PAGE_SIZE);
		if(bSuccess)	//读取当前页数据成功
		{
			// 擦除当前页数据
			bSuccess = Flash_Erase_Page(FLASH_START_ADDR + nPage * FLASH_PAGE_SIZE);
			if (bSuccess)
			{
				// 写入数据到buffer
				for(int i = 0; i < nLength; i++)
				{
					buff[nOffset + i] = pData[i];
				}
				// 将buffer数据写入Flash
				bSuccess = Flash_Write_Page(FLASH_START_ADDR + nPage * FLASH_PAGE_SIZE, buff);
			}			
		}
//		if(NULL != buff)
//		{
//			delete[] buff;
//			buff = NULL;
//		}
	}
	else	//当前页剩余空间不足以容纳待写入数据
	{
		
	}
	
	return bSuccess;
}

void Flash_Erase(uint32_t nAddr, uint16_t nLength)
{
	//TODO
}

